<script lang="ts" setup>
import Form from '@/components/Form.vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'

const props = defineProps<{
    // 从父组件传递过来的必选参数，决定是否显示对话框
    visible: Boolean
    // 从父组件传递过来的可选type参数，决定对话框的类型
    type?: 'login' | 'signup'
}>()
// 向父组件发送完成事件
const emit = defineEmits(['success'])
const userStore = useUserStore()
const width = ref('30%')
// 重置对话框宽度
const resize = () => {
    if (window.innerWidth < 768) {
        width.value = '90%'
    } else if (window.innerWidth < 1000) {
        width.value = '60%'
    } else {
        width.value = '30%'
    }
}
onMounted(() => {
    resize()
    // 监听窗体大小变化
    window.addEventListener('resize', resize)
})

function open() {
    if (!userStore.isLogged) {
        // 重置邮箱
        userStore.user.email = ''
    } else {
        ElMessage.warning(`您已登录，无需重复${props.type === 'signup' ? '注册' : '登录'}`)
        close()
    }
}

function close() {
    userStore.user.password = ''
    userStore.user.confirmPassword = ''
    emit('success')
}
</script>

<template>
    <!--
      关闭弹窗前务必通知父组件，否则关闭后父组件中控制本组件是否显示的变量不会被重置
   -->
    <el-dialog
        :close-on-click-modal="false"
        :model-value="visible"
        :title="type === 'signup' ? '注册' : '登录'"
        :width="width"
        align-center
        center
        destroy-on-close
        draggable
        @close="close"
        @open="open">
        <Form :type="type" @success="emit('success')" />
    </el-dialog>
</template>